package com.jinyang.jetpackdemo.activity

import android.app.AlertDialog
import android.app.Dialog
import android.content.Intent
import android.net.Uri
import android.os.*
import android.provider.Settings
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.widget.RelativeLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.google.android.material.snackbar.BaseTransientBottomBar
import com.google.android.material.snackbar.Snackbar
import com.jinyang.jetpackdemo.R
import com.jinyang.jetpackdemo.util.application.ApplicationUtil
import com.jinyang.jetpackdemo.util.gson.GsonUtils
import kotlinx.android.synthetic.main.activity_handler.*
import kotlinx.coroutines.launch

class HandlerActivity : AppCompatActivity() {
    private lateinit var handlerThread: HandlerThread
    var handler: Handler = object : Handler(Looper.myLooper()!!) {
        override fun handleMessage(msg: Message) {
            //这里接受并处理消息
            log(GsonUtils.toJson(msg))
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_handler)
        btn_sendMessage.setOnClickListener {
            handler.sendEmptyMessage(111)
            handler.sendEmptyMessageDelayed(222, 500)
            handler.sendEmptyMessageAtTime(333, SystemClock.uptimeMillis() + 1000)
            val msg4 = Message.obtain()
            msg4.what = 444
            handler.sendMessage(msg4)
            handler.sendMessage(handler.obtainMessage(555))
            handler.sendMessageDelayed(Message.obtain(handler, 666), 300)
            handler.sendMessageAtTime(
                Message.obtain(handler, 777),
                SystemClock.uptimeMillis() + 700
            )
            handler.sendMessageAtFrontOfQueue(handler.obtainMessage(888))//立即发送Message到队列，而且是放在队列的最前面
            handler.post {
                log("handler.post(Runnable())")
            }
            handler.postDelayed({
                log("handler.postDelayed(Runnable(),100)")
            }, 100)
            handler.postAtTime({
                log("handler.postAtTime(Runnable(),uptimeMillis()+200)")
            }, SystemClock.uptimeMillis() + 200)
            handler.postAtFrontOfQueue {
                log("handler.postAtFrontOfQueue(Runnable())")
            }
        }
        val thread = LooperThread(Runnable {
            log("LooperThread.Runnable.run()")

        })
        thread.start()
        var temp = 1000
        btn_sendInThread.setOnClickListener {
            thread.mHandler.sendEmptyMessage(++temp)
        }
        btn_Snackbar.setOnClickListener {
            Snackbar.make(it, "Hello SnackBar!", Snackbar.LENGTH_SHORT).show();
            val snackBar = Snackbar.make(it, "Hello SnackBar!", Snackbar.LENGTH_SHORT)
            snackBar.addCallback(object : Snackbar.Callback() {
                override fun onDismissed(snackbar: Snackbar?, event: Int) {
                    super.onDismissed(snackbar, event)
                    when (event) {
                        BaseTransientBottomBar.BaseCallback.DISMISS_EVENT_ACTION -> log("Snackbar通过Action的点击事件退出")
                        BaseTransientBottomBar.BaseCallback.DISMISS_EVENT_CONSECUTIVE -> log("Snackbar由于新的Snackbar显示而退出")
                        BaseTransientBottomBar.BaseCallback.DISMISS_EVENT_MANUAL -> log("Snackbar通过调用dismiss()方法退出")
                        BaseTransientBottomBar.BaseCallback.DISMISS_EVENT_SWIPE -> log("Snackbar右划退出")
                        BaseTransientBottomBar.BaseCallback.DISMISS_EVENT_TIMEOUT -> log("Snackbar自然退出")
                    }
                }

                override fun onShown(snackbar: Snackbar?) {
                    super.onShown(snackbar)
                    log("Snackbar显示")
                }
            })
            snackBar.setAction("ok") { log("snackBar click ok btn") }
            snackBar.show();
        }

        btn_testHandlerThread.setOnClickListener {
            testHandlerThread()
        }
        btn_HandlerThreadQuit.setOnClickListener {
            handlerThread.quit()
        }
        btn_HandlerThreadQuitSafely.setOnClickListener {
            handlerThread.quitSafely()
        }
    }

    private fun testHandlerThread() {
        handlerThread = HandlerThread("num++")
        handlerThread.start()
        val handler = Handler(handlerThread.looper) { msg ->
            log("handlerThread 子线程工作:" + msg.what)
            val message = Message.obtain()
            message.what = msg.what * 10
            Thread.sleep(2000)
            mainHandler.sendMessage(message)
            false
        }
        lifecycleScope.launch {
//            for (i in 0..10) {
////                delay(1000)
//                handler.sendEmptyMessage(i)
//            }
            for (i in 0..10) {
//                delay(1000)
                handler.sendEmptyMessageDelayed(i, i * 1000L)
            }
        }
    }

    var mainHandler: Handler = object : Handler(Looper.myLooper()!!) {
        override fun handleMessage(msg: Message) {
            log("mainHandler 更新UI:" + msg.what)
        }
    }

    class LooperThread(val target: Runnable? = null) : Thread() {
        lateinit var mHandler: Handler
        override fun run() {
//            super.run()
            target?.run()
            Looper.prepare()
//            Looper.loop()//lateinit property mHandler has not been initialized
            //因为loop方法中有一个for (;;) 死循环，下面的代码就不会执行了，所以应该先初始化handler，再调用loop()
//            mHandler = object : Handler(Looper.myLooper()!!) {
            mHandler = object : Handler(Looper.getMainLooper()) {
                override fun handleMessage(msg: Message) {
                    super.handleMessage(msg)
                    log(GsonUtils.toJson(msg))
                    Toast.makeText(
                        ApplicationUtil.instance.getAppContext(),
                        "子线程Handler(Looper.getMainLooper())中的Toast",
                        Toast.LENGTH_SHORT
                    ).show()
                    //Should be called from the main thread, not Thread[Thread-3,5,main]
                    val result = Toast(ApplicationUtil.instance.getAppContext())
                    val contentRl = View.inflate(
                        ApplicationUtil.instance.getAppContext(),
                        R.layout.toast_common,
                        null
                    ) as RelativeLayout
                    (contentRl.findViewById<View>(R.id.tv_toast_common) as TextView).text =
                        "[${Thread.currentThread().name}] 子线程中 new 的Toast"
                    result.view = contentRl
                    result.setGravity(Gravity.BOTTOM, 0, 200)
                    result.show()
                    //子线程中的AlertDialog
                    //Should be called from the main thread, not Thread[Thread-3,5,main]
                    //Unable to add window -- token null is not valid; is your activity running?
                    val builder: AlertDialog.Builder =
                        AlertDialog.Builder(ApplicationUtil.instance.getAppContext())
                    builder.setMessage("Hello,子线程中的AlertDialog")
                    builder.setNegativeButton("CANCEL", null)
                    builder.setPositiveButton("OK") { dialog, which ->
                        dialog.dismiss()
                    }
                    val dialog: Dialog = builder.create()
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//6.0
                        if (!Settings.canDrawOverlays(ApplicationUtil.instance.getAppContext())) {
                            //启动Activity让用户授权
                            val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
                            // Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
                            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                            intent.data =
                                Uri.parse("package:${ApplicationUtil.instance.getAppContext()?.packageName}");
                            ApplicationUtil.instance.getAppContext()?.startActivity(intent)
                            return
                        }
                        dialog.window?.setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY)
                    } else {
                        dialog.window?.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT)
                    }
                    dialog.show()
                }
            }
            //子线程中的Toast
            // Can't toast on a thread that has not called Looper.prepare()
            Toast.makeText(
                ApplicationUtil.instance.getAppContext(),
                "[${Thread.currentThread().name}] 子线程中的Toast",
                Toast.LENGTH_SHORT
            ).show()

            Looper.loop()
        }


    }

    override fun onDestroy() {
        handler.removeCallbacksAndMessages(null)
        super.onDestroy()
    }

}